package com.ocean.tree;

import java.util.*;

/**
 * https://leetcode.cn/problems/n-ary-tree-postorder-traversal/
 * n叉树后续遍历
 */
public class NAryTreePostorderTraversal2 {

    public static void main(String[] args) {
        Node root = Node.getRoot();
        NAryTreePostorderTraversal2 traversal = new NAryTreePostorderTraversal2();
        List<Integer> res = traversal.postorder2(root);
        System.out.println(res);
    }

    public List<Integer> postorder(Node root) {
        List<Integer> res = new ArrayList<>();
        postorder(root, res);
        return res;
    }


    // [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
    public void postorder(Node root, List<Integer> res) {
        if (root == null) {
            return;
        }
        if (root.children != null && !root.children.isEmpty()) {
            for (Node child : root.children) {
                postorder(child, res);
            }
        }
        res.add(root.val);
    }


    public List<Integer> postorder2(Node root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Deque<Node> stack = new LinkedList<>();
        stack.push(root);
        Set<Node> visited = new HashSet<>();
        while (!stack.isEmpty()) {
            Node cur = stack.peek();
            if (cur.children == null || cur.children.isEmpty() || visited.contains(cur)) {
                res.add(cur.val);
                stack.pop();
                continue;
            }
            for (int i = cur.children.size() - 1; i >= 0; i--) {
                stack.push(cur.children.get(i));
            }
            visited.add(cur);
        }
        return res;
    }


}
